﻿using K3Cloud.WebApi.Core.IoC;
using K3Cloud.WebApi.Core.IoC.Cache;
using MyRedisLibrary.Microsoft.Extensions.Caching.Distributed;
using MyRedisLibrary.RedisCaches;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

namespace WebDemo
{
    /// <summary>
    /// 自定义的缓存服务
    /// </summary>
    public class MyRedisCache(IDistributedCache cache) : ICacheService
    {
        private readonly IDistributedCache cache = cache;

        public void Add<V>(string key, V value)
        {
            Add(key, value, 20 * 60);
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            cache.Add(key, value, cacheDurationInSeconds);
        }
        public bool ContainsKey<V>(string key)
        {
            try
            {
                return cache.ContainsKey(key);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                K3Scoped.Client.DefaultCache();
                return false;
            }
        }

        public V Get<V>(string key)
        {
            return cache.Get<V>(key);
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            return cache.GetAllKey<V>();
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            return cacheDurationInSeconds == 0 ? create() : cache.GetOrCreate<V>(cacheKey, create, cacheDurationInSeconds);
        }

        public void Remove<V>(string key)
        {
            cache.Remove(key);
        }
        public void RemoveAll()
        {
            RedisCacheOptions options = cache.GetType().BaseType?.GetField("_options", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(cache) as RedisCacheOptions;
            string instanceName = options?.InstanceName;
            foreach (string key in cache.GetAllKey<object>())
            {
                if (instanceName != null && key.StartsWith(instanceName))
                {
                    cache.Remove<object>(key[instanceName.Length..]);
                }
                else
                {
                    cache.Remove<object>(key);
                }
            }
        }
    }
}
